package com.zzh.takeoutapp.base;

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;

import java.util.Iterator;
import java.util.Stack;

/**
 * 项目名称：
 * 类描述：
 * 创建人：
 * 创建时间：
 * 修改人：
 * 修改时间：
 * 修改备注：
 */
public class AppManager {
    private static Stack<AppCompatActivity> activityStack;
    private static AppManager instance;

    private AppManager() {
    }

    public static AppManager getAppManager() {
        if(instance == null) {
            instance = new AppManager();
        }

        return instance;
    }

    public void addActivity(AppCompatActivity activity) {
        if(activityStack == null) {
            activityStack = new Stack();
        }

        activityStack.add(activity);
    }

    public AppCompatActivity currentActivity() {
        if(activityStack != null && !activityStack.isEmpty()) {
            AppCompatActivity activity = (AppCompatActivity)activityStack.lastElement();
            return activity;
        } else {
            return null;
        }
    }

    public AppCompatActivity findActivity(Class<?> cls) {
        AppCompatActivity activity = null;
        Iterator i$ = activityStack.iterator();

        while(i$.hasNext()) {
            AppCompatActivity aty = (AppCompatActivity)i$.next();
            if(aty.getClass().equals(cls)) {
                activity = aty;
                break;
            }
        }

        return activity;
    }

    public void finishActivity() {
        AppCompatActivity activity = (AppCompatActivity)activityStack.lastElement();
        this.finishActivity((Activity) activity);
    }

    public void finishActivity(Activity activity) {
        if(activity != null) {
            activityStack.remove(activity);
            activity.finish();
            activity = null;
        }

    }

    public void finishActivity(Class<?> cls) {
        boolean flag = false;
        AppCompatActivity repa = null;
        Iterator it = activityStack.iterator();

        while(it.hasNext()) {
            repa = (AppCompatActivity)it.next();
            if(repa.getClass() == cls) {
                it.remove();
                flag = true;
                break;
            }
        }

        if(flag && repa != null) {
            repa.finish();
            repa = null;
        }

    }

    public void finishOthersActivity(Class<?> cls) {
        Iterator i$ = activityStack.iterator();

        while(i$.hasNext()) {
            AppCompatActivity activity = (AppCompatActivity)i$.next();
            if(!activity.getClass().equals(cls)) {
                this.finishActivity((Activity)activity);
            }
        }

    }

    public void finishAllActivity() {
        int i = 0;

        for(int size = activityStack.size(); i < size; ++i) {
            if(null != activityStack.get(i)) {
                ((AppCompatActivity)activityStack.get(i)).finish();
            }
        }

        activityStack.clear();
    }


}
